package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegisVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegisVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity =memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status",1));
        memberEntity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一，为了让controller能感知异常，异常机制
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", vo.getPhone()));
        if (mobile>0){
            throw new PhoneExistException();
        }
        Integer username = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", vo.getUserName()));
        if (username>0){
            throw new UsernameExistException();
        }
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        //加密存储 springSecurity带的加密器
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);



        baseMapper.insert(memberEntity);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("mobile", loginacct).or().eq("username", loginacct));
        if (memberEntity==null){
            return null;
        }
        String passwordDb = memberEntity.getPassword();
        //密码匹配
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(password, passwordDb);
        if (!matches){
            return null;
        }

        return memberEntity;
    }

    @Override
    public MemberEntity oauthLogin(Map<String,String> accessMap) {
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("source_uid", accessMap.get("uid")));
        if (memberEntity!=null){
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(accessMap.get("access_token"));

            baseMapper.updateById(entity);

            memberEntity.setAccessToken(accessMap.get("access_token"));

            return memberEntity;
        }
        //没有注册过
        MemberEntity regist = new MemberEntity();

        long uid = Long.parseLong(accessMap.get("uid"));
        //access_token换取用户信息
        String accessToken = accessMap.get("access_token");
        String userInfoUrl="https://api.weibo.com/2/users/show.json?access_token="+accessToken+"&uid="+uid;
        String userInfo = HttpUtils.doGet(userInfoUrl);
        Map<String,Object> userInfoMap = JSON.parseObject(userInfo, Map.class);
        //将用户信息保存数据库
        regist.setAccessToken(accessToken);
        regist.setSourceType(1);
        regist.setSourceUid(accessMap.get("uid"));
        regist.setUsername(String.valueOf(userInfoMap.get("screen_name")));
        regist.setGender(String.valueOf(userInfoMap.get("gender")).equals("m")?1:0);
        regist.setHeader(String.valueOf(userInfoMap.get("avatar_hd")));

        baseMapper.insert(regist);

        return regist;
    }

}